﻿//////////////////////////////////////////////////////////////////////
// <copyright file=Edge.cs">
//     Copyright (c) 2010
//     Released under  GNU GENERAL PUBLIC LICENSE
//     http://dev.perl.org/licenses/gpl1.html
// </copyright>
// <date> 3/28/2010 3:14:28 PM </date>
// <author> B. Endrovski </author>
// <web> http://furiouspixels.blogspot.com/ </web>
//////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ContourReconstruction
{
	public class Edge
	{
		public Vector2D A { get; set; }
		public Vector2D B { get; set; }
		public List<Triangle> Triangles { get; private set; }

		/// <summary>
		/// Is it an interior edge?
		/// </summary>
		public bool IsInterior
		{
			get { return Triangles.Count == 2; }
		}

		/// <summary>
		/// Is it an exterior edge?
		/// </summary>
		public bool IsExterior
		{
			get { return Triangles.Count == 1; }
		}

		/// <summary>
		/// New edge from end points
		/// </summary>
		public Edge(Vector2D A, Vector2D B)
		{
			this.A = A;
			this.B = B;
			Triangles = new List<Triangle>(2);
		}

		/// <summary>
		/// Checks of two edges are equal (direction ignored)
		/// </summary>
		public static bool operator ==(Edge first, Edge second)
		{
			return ( first.A == second.A && first.B == second.B) ||
					(first.A == second.B && first.B == second.A);
		}

		/// <summary>
		/// Checks of two edges are not equal (direction ignored)
		/// </summary>
		public static bool operator !=(Edge e1, Edge e2)
		{
			return !(e1 == e2);
		}

		/// <summary>
		/// Overrides GetHashCode() to be able to use the HashSet
		/// </summary>
		public override int GetHashCode()
		{
			return A.GetHashCode() ^ B.GetHashCode();	// Plain XOR (makes the order irrevelant)
		}

		/// <summary>
		/// Also nedded for hasing
		/// </summary>
		public override bool Equals(object obj)
		{
			return (obj as Edge) == this;
		}

		/// <summary>
		/// Shortcut for getting a neighbour for triagle "over" the edge
		/// </summary>
		public Triangle GetNeighbour(Triangle t)
		{
			int i = Triangles.IndexOf(t);
			if (i >= 0 && Triangles.Count > 1)
				return Triangles[(i + 1) % 2];
			else
				return null;
		}
	}
}
